%% Fig.7(a)
clc; clear; close all;

%% —— 参数设置 —— 
g11     = 1.4;  
g12     = -2;
g21     = 1.4;  
g22     = 1.6;
k       = 2.6;
N       = 2;           
E       = 2*N + 0.5;   % 4.5

dt      = 0.01;
t_trans = 20;          
t_end   = 1000;

%% —— 丢弃 transient —— 
x = [0.01;0;0];
for i = 1:round(t_trans/dt)
    x = RK4(@(x) IMBNHNN(x,k,g11,g12,g21,g22,E), x, dt);
end

%% —— 记录吸引子轨迹 —— 
n_rec = round((t_end - t_trans)/dt);
X     = zeros(3, n_rec+1);
X(:,1)= x;
for i = 1:n_rec
    x = RK4(@(x) IMBNHNN(x,k,g11,g12,g21,g22,E), x, dt);
    X(:,i+1) = x;
end

% 分离分量
x1 = X(1,:);   % X 轴
x2 = X(2,:);   % Z 轴
x3 = X(3,:);   % Y 轴

% 找到 x2=0 平面穿越点的索引
idx = find(x2(1:end-1).*x2(2:end) < 0) + 1;

%% —— 绘图 —— 
figure; hold on;

% ===== 在绘图之前，先生成一张网格 =====
[X1p,X3p] = meshgrid( ...
    linspace(min(x1), max(x1), 30), ...
    linspace(min(x3), max(x3), 30) );

% ===== 用 surf 在 z=0 平面绘制洋红色半透明面 =====
surf( X1p, X3p, zeros(size(X1p)), ...
      'FaceColor','m', ...      % 面片填充色：洋红
      'FaceAlpha',0.3, ...      % 半透明
      'EdgeColor','none' );     % 无边缘线


% 1) 三维主轨迹
plot3(x1, x3, x2, 'Color',[0.3 0.3 0.3],'LineWidth',0.8);

% 2) z=-3 平面上的灰色投影
plot3(x1, x3, -3*ones(size(x1)), '.', ...
      'Color',[0.7 0.7 0.7],'MarkerSize',2);

% 3) z=-2 平面上的 magenta 交点
plot3(x1(idx), x3(idx), -3*ones(size(idx)), 'm.','MarkerSize',8);

view(45,25);
xlabel('x_1'); ylabel('x_3'); zlabel('x_2');
grid on; axis tight;

%% —— 本地函数 —— 

function dx = IMBNHNN(x, k, g11, g12, g21, g22, E)
    % 嵌套余弦记忆电导 IMBN-HNN 模型
    sat = 0.5*(abs(x(3) + E) - abs(x(3) - E));  % 饱和函数 Sat(x3)
    dx      = zeros(3,1);
    dx(1)   = -x(1) + g11*tanh(x(1)) + g12*tanh(x(2)) ...
              + k*cos(pi*sat)*x(1);
    dx(2)   = -x(2) + g21*tanh(x(1)) + g22*tanh(x(2));
    dx(3)   =  x(1);
end